﻿using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using SingleUserMall.Common;
using SingleUserMall.Complains.Form;
using SingleUserMall.Complains.VO;
//using SingleUserMall.Workers.Form;
//using SingleUserMall.Workers.VO;
using System.Linq;
using System.Threading.Tasks;

namespace SingleUserMall.Complains
{
    [AbpAuthorize]
    public class ComplainManageAppService : SingleUserMallAppServiceBase, IComplainManageAppService
    {
        private readonly IRepository<Complain,long> _complainRepository;
        public ComplainManageAppService(IRepository<Complain,long> complainRepository)
        {
            _complainRepository = complainRepository;
        }
        public async Task<ComplainViewVO> GetComplainAsync(SingleId<long> form)
        {
            var complain = await _complainRepository.FirstOrDefaultAsync(form.Id);
            return complain.ToVO<Complain, ComplainViewVO>((w, vo) =>
            {
                vo.inUser = w.User;
            });
        }

        public async Task<PagedResultDto<ComplainViewVO>> GetComplainsBySearchAsync(ComplainSearchForm form)
        {
            var query = _complainRepository.GetAll()
                .WhereIf(!string.IsNullOrEmpty(form.Keywords), x => x.User.Name.Contains(form.Keywords))
                .WhereIf(form.ComplainType.HasValue, x=> x.ComplainType == form.ComplainType)
                .WhereIf(form.Status.HasValue, x => x.Status == form.Status)
                .OrderByDescending(x => x.CreationTime);
            return await query.ToPagedResultDtoAsync<Complain, ComplainViewVO>(form,(w,vo)=>
            {
                vo.inUser = w.User;
            });
        }

        public async Task SaveComplainAsync(ComplainForm form)
        {
            var complain = await _complainRepository.FirstOrDefaultAsync(form.Id);
            if (complain != null)
            {
                complain = form.MapTo(complain);
                await _complainRepository.UpdateAsync(complain);
            }
            else
            {
                complain = form.MapTo<Complain>();
                await _complainRepository.InsertAsync(complain);
            }
        }

        public async Task VerifyComplainAsync(ComplainAuditForm form)
        {
            var complain = await _complainRepository.FirstOrDefaultAsync(form.Id);
            complain.Status = form.IsPass ? ComplainVerifyStatus.Audited : ComplainVerifyStatus.Rejected;
            complain.Remark = form.Remark;
        }

        public async Task RemoveAsync(SingleId<long> form)
        {
            await _complainRepository.DeleteAsync(form.Id);
        }
    }
}
